package com.lucy.disk.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.disk.domain.entity.FileEntity;
import com.lucy.disk.service.FileService;
import com.lucy.disk.utils.DiskUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("disk")
@Api(tags = "虚拟路径")
public class VirtualPathController {
    @Autowired
    FileService fileService;



    @GetMapping("file/tree")
    @ApiOperation(value = "文件树构建",notes = "")
    public ResponseDTO<Object> fileTreeBuild(
            @RequestParam(value = "userId",required = false) String userId,
            @RequestParam(value = "fileId",required = false) String fileId,
            @RequestParam(value = "isDir",required = false) Integer isDir
    ){
        FileEntity fileEntity = new FileEntity();
        // 如果没传递 -- 根据TOKEN判断当前登录用户
        if (Validator.isEmpty(userId)){
            userId = StpUtil.getLoginIdAsString();
        }

        fileEntity.setUserId(userId);
        // 如果限制为目录--加入限制条件
        // 2022-09-08 修复 不传 isDir 报错问题
        if (Validator.isNotEmpty(isDir) && isDir.equals(1)){
            fileEntity.setIsDir(isDir);
        }

        Example<FileEntity> example = Example.of(fileEntity);
        List<FileEntity> files = fileService.getExample(example);
        System.out.println(files.size());
        // rootId 配置
        String rootId = "";
        if (Validator.isNotEmpty(fileId)){
            System.out.println("fileId不为空");
            rootId = fileId;
        }

        return ResponseDTO.succData(
                DiskUtil.fileTreeBuild(files,rootId)
        );
    }
    /**
     * 冗余方法，不推荐使用
     * @param paths
     * @param userId
     * @return
     */
    @Deprecated
    @GetMapping("path/file")
    @ApiOperation(value = "路径定位",notes = "")
    public ResponseDTO<Object> getPathFile(@RequestParam("paths") List<String> paths, @RequestParam(value = "userId",required = false) String userId){
        if (Validator.isEmpty(userId)){
            userId = StpUtil.getLoginIdAsString();
        }
        FileEntity fileEntity = new FileEntity();
        fileEntity.setUserId(userId);
        Example<FileEntity> example = Example.of(fileEntity);
        List<FileEntity> files = fileService.getExample(example);
        List<Tree<String>> treeList = DiskUtil.fileTreeBuild(files,"");
        // 根据文件树检索
        int pathIndex = 0;
        List<String> ids = new ArrayList<>();
        while (pathIndex < paths.size()){
            String fileName = paths.get(pathIndex);
            System.out.println("当前检索:"+fileName);
            List<Tree<String >> tmpTree = new ArrayList<>();
            for(Tree<String> tree:treeList){
                if (tree.getName().equals(fileName)){
                    ids.add(tree.getId());
                    tmpTree = tree.getChildren();
                }
            }

            treeList = tmpTree;
            pathIndex = pathIndex + 1;
        }
        if (ids.size() != paths.size()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到对应路径文件");
        }
        return ResponseDTO.succData(
                ids
        );

    }

    @GetMapping("file/{fileId}/path")
    @ApiOperation(value = "文件虚拟路径",notes = "")
    public ResponseDTO<Object> fileVirtualPath(@PathVariable("fileId") String fileId){
        String loginId = StpUtil.getLoginIdAsString();
        FileEntity fileEntity = new FileEntity();
        fileEntity.setUserId(loginId);
        Example<FileEntity> example = Example.of(fileEntity);
        List<FileEntity> files = fileService.getExample(example);
        List<Tree<String>> treeList = DiskUtil.fileTreeBuild(files,"");
        Tree<String> pathTree = null;
        for (Tree<String> tree:treeList){

            if (Validator.isNotEmpty(tree.getNode(fileId))){
                //  System.out.println(tree.getNode(fileId).toString());
                pathTree = tree;
            }
        }
        List<String> path = new ArrayList<>();
        List<String> idPath = new ArrayList<>();
        while (!fileId.equals("")){

            assert pathTree != null;
            Tree<String> tmptree = pathTree.getNode(fileId);
            path.add(tmptree.getName().toString());
            idPath.add(tmptree.getId());
            fileId = tmptree.getParentId();
        }
        path = path.stream().sorted((pre, next) -> -1).collect(Collectors.toList());
        idPath = idPath.stream().sorted((pre, next) -> -1).collect(Collectors.toList());
        Map<String,Object> res = new HashMap<>();
        res.put("path",path);
        res.put("idPath",idPath);
        return ResponseDTO.succData(
                res
        );
    }
}
